package com.application.lucky.fragment.main;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.view.LayoutInflater;
import android.view.View;

import com.application.lucky.R;
import com.application.lucky.activity.NewFriendsActivity;
import com.application.lucky.activity.PbChatActivity;
import com.application.lucky.adapter.FriendsAdapter;
import com.application.lucky.bean.eventbean.FriendEvent;
import com.application.lucky.bean.eventbean.HomePointEvent;
import com.application.lucky.bean.jsonBean.FriendApplyBean;
import com.application.lucky.bean.jsonBean.FriendBean;
import com.application.lucky.bean.jsonBean.FriendListbean;
import com.application.lucky.bean.jsonBean.UiBean;
import com.application.lucky.config.Config;
import com.application.lucky.manager.ContactsManager;
import com.application.lucky.request.CallBackEx;
import com.application.lucky.request.FriendRequest;
import com.application.lucky.widget.TitlebarView;
import com.application.lucky.widget.popupwindow.HomeAddPop;
import com.application.lucky.widget.popupwindow.HomeSearchPop;
import com.application.lucky.widget.slidebar.FriendsComparator;
import com.application.lucky.widget.slidebar.PinyinUtils;
import com.application.lucky.widget.slidebar.SideBar;
import com.application.mylibrary.base.BaseFragment;
import com.application.mylibrary.utils.EventBusUtils;
import com.application.mylibrary.utils.LogUtils;
import com.application.mylibrary.utils.ToastUtils;
import com.application.mylibrary.widget.RefreshView;
import com.baselib.libnetwork.net.libnetworkcomponent.BaseResponse;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.qunar.im.base.common.ConversitionType;

import org.greenrobot.eventbus.Subscribe;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class FragmentContacts extends BaseFragment {

    private com.application.lucky.widget.slidebar.SideBar countrySidebar;
    private com.application.mylibrary.widget.RefreshView refreshView;
    private FriendsAdapter adapter;
    private LinearLayoutManager manager;
    private TitlebarView titlBar;
    private HomeSearchPop homeSearchPop;
    private HomeAddPop pop;
    private FriendRequest request;
    private View redPoint;


    @Override
    protected void beforeInit(Bundle arguments) {

    }

    @Override
    public boolean registerEventBus() {
        return true;
    }

    @Override
    public int getLayoutId() {
        return R.layout.fragment_contacts;
    }

    @Override
    public void initView(View view) {
        request = new FriendRequest();
        titlBar = view.findViewById(R.id.title_bar);
        titlBar.setOnViewClick(new TitlebarView.onViewClick() {
            @Override
            public void leftClick() {

            }

            @Override
            public void rightClick() {
                if (pop == null) {
                    pop = new HomeAddPop(mCOntext);
                }
                pop.showAsDropDown(titlBar.getIv_right());
            }
        });
        titlBar.getIv_right2().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                if (homeSearchPop == null) {
                    homeSearchPop = new HomeSearchPop(mCOntext);
                }
                homeSearchPop.show(titlBar);


            }
        });
        countrySidebar = view.findViewById(R.id.country_sidebar);
        refreshView = view.findViewById(R.id.refresh_view);
        android.support.v7.widget.RecyclerView rclList = view.findViewById(R.id.rcl_list);
        manager = new LinearLayoutManager(mCOntext);
        adapter = new FriendsAdapter(R.layout.item_friend_adapter);

        adapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                UiBean item = FragmentContacts.this.adapter.getItem(position);
                if (item != null) {
                    //RED_USER_23@roamblue
                    Intent intent = new Intent(mCOntext, PbChatActivity.class);
                    intent.putExtra(PbChatActivity.KEY_JID, Config.IMIdUtils.getIMUid(item.id));
                    intent.putExtra(PbChatActivity.KEY_CHAT_TYPE, String.valueOf(ConversitionType.MSG_TYPE_CHAT));
                    intent.putExtra(PbChatActivity.KEY_IS_CHATROOM, false);
                    startActivity(intent);
                } else {
                    ToastUtils.show("点击好友出现错误。。。。");
                }
            }
        });
        rclList.setLayoutManager(manager);
        rclList.setAdapter(adapter);
        adapter.addHeaderView(getHeadView());
        initListener();
        loadData();
    }


    private void loadData() {
        request.friend_list("0", new CallBackEx<BaseResponse<FriendListbean>>() {
            @Override
            public void onSuccess(BaseResponse<FriendListbean> friendListbeanBaseResponse) {
                refreshView.setFinish();
                FriendListbean dataInfo = friendListbeanBaseResponse.dataInfo;

                if (dataInfo != null) {

                    List<FriendListbean.FriendListBean> friendList = dataInfo.getFriendList();
                    List<FriendBean> beans = new ArrayList<>();
                    if (friendList == null) {
                        adapter.setNewData(new ArrayList<UiBean>());
                        return;
                    }
                    ContactsManager.getInstance().addData(friendList);
                    for (int i = 0; i < friendList.size(); i++) {
                        FriendBean user = friendList.get(i).getUser();
                        if (user != null) {
                            beans.add(user);
                        }
                    }
                    List<UiBean> uiBeans = filledData(beans);
                    Collections.sort(uiBeans, new FriendsComparator());
                    adapter.setNewData(uiBeans);
                }
                EventBusUtils.post(new FriendListbean());
            }

            @Override
            public void onFailed(int code) {
                LogUtils.i("hahahhahaha");
            }


        });

    }

    @Subscribe
    public void friendChange(FriendEvent event) {
        loadData();
        loadApply();
    }

    private View getHeadView() {
        View view = LayoutInflater.from(mCOntext).inflate(R.layout.view_fragment_contact_head, null);
        view.findViewById(R.id.rl_kefu).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(getContext(), PbChatActivity.class);
                intent.putExtra(PbChatActivity.KEY_JID, Config.IMIdUtils.getIMUid(Config.KEFU_ID));
                intent.putExtra(PbChatActivity.KEY_CHAT_TYPE, String.valueOf(ConversitionType.MSG_TYPE_CHAT));
                intent.putExtra(PbChatActivity.KEY_IS_CHATROOM, false);
                startActivity(intent);
//                startActivity(new Intent(getContext(), KeFuActivity.class));
            }
        });
        view.findViewById(R.id.rl_new_friends).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivityAnim(new Intent(mCOntext, NewFriendsActivity.class));
            }
        });
        redPoint = view.findViewById(R.id.view_point);
        return view;
    }

    private void initListener() {
        countrySidebar.setOnTouchingLetterChangedListener(new SideBar.OnTouchingLetterChangedListener() {
            @Override
            public void onTouchingLetterChanged(String s) {
                int position = adapter.getPositionForSection(s.charAt(0));
                if (position != -1) {
                    manager.scrollToPositionWithOffset(position, 0);
                }

            }
        });
        adapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {

            }
        });
        refreshView.setRefreshListener(new RefreshView.RefreshListener() {
            @Override
            public void onRefresh() {
                loadData();
            }
        });
    }

    private List<UiBean> filledData(List<FriendBean> date) {
        List<UiBean> mSortList = new ArrayList<>();

        for (int i = 0; i < date.size(); i++) {
            UiBean sortModel = new UiBean();
            sortModel.name = date.get(i).getShowName();
            sortModel.id = date.get(i).getUserId() + "";
            sortModel.avatarUrl = date.get(i).getHeadPic() + "";


            //汉字转换成拼音
            String pinyin = PinyinUtils.getPingYin(date.get(i).getNickName());
            String sortString = pinyin.substring(0, 1).toUpperCase();

            // 正则表达式，判断首字母是否是英文字母
            if (sortString.matches("[A-Z]")) {
                sortModel.letters = (sortString.toUpperCase());
            } else {
                sortModel.letters = ("#");
            }

            mSortList.add(sortModel);
        }
        return mSortList;

    }


    private void loadApply() {
        request.friend_apply_list(0 + "", new CallBackEx<BaseResponse<FriendApplyBean>>() {

            @Override
            public void onSuccess(BaseResponse<FriendApplyBean> stringBaseResponse) {
                FriendApplyBean dataInfo = stringBaseResponse.dataInfo;
                if (getView() != null) {
                    if (dataInfo != null) {
                        List<FriendApplyBean.FriendListBean> friendList = dataInfo.getFriendList();
                        if (friendList != null) {
                            redPoint.setVisibility(View.VISIBLE);
                        } else {
                            redPoint.setVisibility(View.INVISIBLE);
                        }
                        EventBusUtils.post(new HomePointEvent(HomePointEvent.TAB_contact, friendList != null));
                    }
                }
            }

            @Override
            protected void OnFailureNeedData(int code, BaseResponse<FriendApplyBean> stringBaseResponse) {

            }

            @Override
            public void onFailed(int code) {

            }
        });
    }

    private boolean isHidden = true;

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        isHidden = hidden;
        if (!hidden) {
            loadApply();
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        if (!isHidden)
            loadApply();
    }
}
